package com.bsy.common.base

import android.content.ContentValues
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import androidx.activity.result.ActivityResultLauncher
import androidx.annotation.RequiresApi
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.bsy.common.permission.PermissionInterceptor
import com.bsy.framework.base.BaseDataBindActivity
import com.bsy.framework.base.PermissionRequestCode
import com.bsy.framework.toast.Toaster
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import java.lang.reflect.ParameterizedType

/**
 * 处理系统权限
 */
abstract class BasePermissionActivity<DB : ViewBinding, VM : ViewModel> : BaseDataBindActivity<DB>() {
    lateinit var mViewModel: VM
    private var requestCode: Int = 0

    //拨打电话
    private val callPhone = Permission.CALL_PHONE

    //相机
    private val camera = Permission.CAMERA

    //拍照回调
    private var mActivityResultLauncherTake: ActivityResultLauncher<Intent>? = null

    //相机拍照URI
    var photoUri: Uri? = null

    //相册SD卡权限
    private val sDCard =
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q) mutableListOf(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
        else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) mutableListOf(Permission.READ_MEDIA_IMAGES, Permission.READ_MEDIA_VIDEO)
        else mutableListOf(Permission.MANAGE_EXTERNAL_STORAGE)

    //音频
    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    val SDK13Audio = mutableListOf(Permission.READ_MEDIA_AUDIO)


    override fun onCreate(savedInstanceState: Bundle?) {
        initViewModel()
        super.onCreate(savedInstanceState)

    }

    override fun initParam(intent: Intent?) {
        super.initParam(intent)
    }

    private fun initViewModel() {
        val argument = (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments
        mViewModel = ViewModelProvider(this)[argument[1] as Class<VM>]
    }

    /**
     * 是否拥有相机权限
     */
    private fun hasCameraPermission(): Boolean = XXPermissions.isGranted(this, camera)

    /**
     * 是否拥有相册权限
     */
    private fun hasReadPermission(): Boolean =
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q) XXPermissions.isGranted(
            this,
            mutableListOf(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
        ) else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) XXPermissions.isGranted(
            this,
            mutableListOf(Permission.READ_MEDIA_IMAGES, Permission.READ_MEDIA_VIDEO)
        ) else XXPermissions.isGranted(this, mutableListOf(Permission.MANAGE_EXTERNAL_STORAGE))

    /**
     * 检查摄像头权限
     *
     */
    fun startCheckCameraPermission(code: PermissionRequestCode) {
        if (hasCameraPermission())
            onPermissionPassed(code.value)
        else
            XXPermissions.with(this).interceptor(PermissionInterceptor()).permission(camera).request { _, allGranted ->
                if (allGranted)
                    onPermissionPassed(code.value)
                else
                    Toaster.show("请到设置里开启权限")

            }
    }

    /**
     * 检查申请相册视频权限
     *
     */
    fun startCheckSDCardPermission(code: PermissionRequestCode) {
        this.requestCode = code.value
        if (hasReadPermission())
            onPermissionPassed(code.value)
        else
            startRequestReadAndWriteSd()
    }

    /**
     * 申请相册视频权限
     *
     */

    private fun startRequestReadAndWriteSd() {
        XXPermissions.with(this).interceptor(PermissionInterceptor()).permission(sDCard).request { _, allGranted ->
            if (allGranted)
                onPermissionPassed(requestCode)
            else
                Toaster.show("请到设置里开启权限")
        }
    }

    /**
     * 拥有权限的回调
     *
     */
    abstract fun onPermissionPassed(code: Int)

    /**
     * 打电话权限
     */
    fun startRequestCallPhone(phoneNumber: String) {
        XXPermissions.with(this).interceptor(PermissionInterceptor()).permission(callPhone).request { _, allGranted ->
            if (allGranted) {
                val intent = Intent(Intent.ACTION_DIAL).apply {
                    data = Uri.parse("tel:$phoneNumber")
                    flags = Intent.FLAG_ACTIVITY_NEW_TASK
                }
                this.startActivity(intent)
            } else {
                Toaster.show("请到设置里开启权限")
            }
        }
    }

    /**
     * 调取本地相机拍照
     */
    fun takePictures() {
        val takeIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        val values = ContentValues()
        //根据uri查询图片地址
        photoUri = this.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        //放入拍照后的地址
        takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
        //调起拍照
        mActivityResultLauncherTake?.launch(takeIntent)
    }
}